import MenuToggle from '../components/MenuToggle';
import { CardContent, Card } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import React, { useState } from 'react';
import { DialogContent, DialogTitle, DialogFooter, Dialog, DialogHeader, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { http } from '@/utils/http';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { useQuery } from '@tanstack/react-query';
import { Switch } from '@/components/ui/switch';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { HardDrive, Eye, Trash2, Server, Cloud, Database, CheckCircle, Edit, AlertCircle, Plus, Settings, XCircle } from 'lucide-react';
import { DropdownMenuItem, DropdownMenuTrigger, DropdownMenuContent, DropdownMenu } from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';

const StorageSource = ({ toggleSidebar }) => {
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editingSource, setEditingSource] = useState(null);
  const [selectedSources, setSelectedSources] = useState([]);
  const [isSaving, setIsSaving] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  // 存储源类型配置
  const storageTypes = [
    { value: 'LOCAL', label: '本地存储', icon: HardDrive, sourceCode: 'LOCAL' },
    { value: 'Amazon-S3', label: 'Amazon-S3', icon: Cloud, sourceCode: 'Amazon' },
    { value: 'ALY_OSS', label: '阿里云OSS', icon: Server, sourceCode: 'ALY_OSS' },
    { value: 'TXY_OSS', label: '腾讯云OSS', icon: Cloud, sourceCode: 'TXY_OSS' },
    { value: 'MINIO', label: 'MinIO', icon: Database, sourceCode: 'MINIO' },
    { value: 'FTP', label: 'FTP服务器', icon: Server, sourceCode: 'FTP' }
  ];

  const [newSource, setNewSource] = useState({
    sourceName: '',
    sourceType: 'LOCAL',
    endpoint: '',
    bucketName: '',
    basePath: '',
    region: '',
    secretId: '',
    isDefault: false
  });

  // 使用 useQuery 获取存储源列表
  const { data: storageSources = [], isLoading, error, refetch } = useQuery({
    queryKey: ['storageSources', searchQuery],
    queryFn: async () => {
      const response = await http.post('/storage/stg-source/list', {
        sourceName: searchQuery || undefined,
        sourceType: undefined,
        sourceCode: undefined,
        isEnabled: undefined
      });
      
      if (response.code === "200" && response.msg === "success") {
        return response.data || [];
      } else {
        throw new Error(response.msg || '获取存储源列表失败');
      }
    },
    retry: 2,
    staleTime: 30000
  });

  const getStatusBadge = (sourceStatus, isEnabled) => {
    if (!isEnabled || sourceStatus !== 'ENABLED') {
      return (
        <Badge className="bg-red-100 text-red-800 hover:bg-red-100 flex items-center space-x-1">
          <XCircle className="w-3 h-3" />
          <span>不可用</span>
        </Badge>
      );
    }
    
    return (
      <Badge className="bg-green-100 text-green-800 hover:bg-green-100 flex items-center space-x-1">
        <CheckCircle className="w-3 h-3" />
        <span>正常</span>
      </Badge>
    );
  };

  const getTypeIcon = (sourceCode) => {
    const typeConfig = storageTypes.find(t => t.sourceCode === sourceCode);
    if (typeConfig) {
      const IconComponent = typeConfig.icon;
      return <IconComponent className="w-4 h-4" />;
    }
    return <HardDrive className="w-4 h-4" />;
  };

  const getTypeLabel = (sourceCode) => {
    const typeConfig = storageTypes.find(t => t.sourceCode === sourceCode);
    return typeConfig ? typeConfig.label : sourceCode || '未知类型';
  };

  // 验证表单
  const validateForm = (formData) => {
    const requiredFields = ['sourceName'];
    
    if (['Amazon-S3', 'ALY_OSS', 'TXY_OSS', 'MINIO'].includes(formData.sourceType)) {
      requiredFields.push('endpoint', 'bucketName');
    }
    
    if (formData.sourceType === 'LOCAL') {
      requiredFields.push('basePath');
    }

    for (const field of requiredFields) {
      if (!formData[field] || formData[field].toString().trim() === '') {
        return false;
      }
    }
    
    return true;
  };

  const handleAddSource = async () => {
    // 验证表单
    if (!validateForm(newSource)) {
      alert('请填写所有必填字段');
      return;
    }

    setIsSaving(true);
    
    try {
      // 获取对应的sourceCode
      const selectedType = storageTypes.find(t => t.value === newSource.sourceType);
      const sourceCode = selectedType ? selectedType.sourceCode : newSource.sourceType;

      // 构建请求数据
      const requestData = {
        $action: 'insert',
        sourceName: newSource.sourceName,
        sourceCode: sourceCode,
        sourceType: newSource.sourceType,
        endpoint: newSource.endpoint || '',
        bucketName: newSource.bucketName || '',
        basePath: newSource.basePath || '',
        region: newSource.region || '',
        secretId: newSource.secretId ? parseInt(newSource.secretId) : null,
        isPublic: 0,
        isEnabled: 1,
        sourceStatus: 'ENABLED',
        isDefault: newSource.isDefault ? 1 : 0,
        sourceOwner: null
      };

      // 调用后端接口
      const response = await http.post('/storage/stg-source/save', requestData);
      
      if (response.code === "200" || response.success) {
        // 重置表单
        setNewSource({
          sourceName: '',
          sourceType: 'LOCAL',
          endpoint: '',
          bucketName: '',
          basePath: '',
          region: '',
          secretId: '',
          isDefault: false
        });
        
        setShowAddDialog(false);
        refetch();
        alert('存储源添加成功');
      } else {
        throw new Error(response.msg || response.message || '添加失败');
      }
    } catch (error) {
      console.error('添加存储源失败:', error);
      alert(error.message || '添加存储源失败,请稍后重试');
    } finally {
      setIsSaving(false);
    }
  };

  const handleEditSource = (source) => {
    // 将sourceCode转换为sourceType用于表单显示
    const typeConfig = storageTypes.find(t => t.sourceCode === source.sourceCode);
    
    setEditingSource({
      ...source,
      sourceType: typeConfig ? typeConfig.value : source.sourceCode,
      isDefault: source.isDefault === 1
    });
    setShowEditDialog(true);
  };

  const handleUpdateSource = async () => {
    if (!editingSource) return;

    // 验证表单
    if (!validateForm(editingSource)) {
      alert('请填写所有必填字段');
      return;
    }

    setIsSaving(true);
    
    try {
      // 获取对应的sourceCode
      const selectedType = storageTypes.find(t => t.value === editingSource.sourceType);
      const sourceCode = selectedType ? selectedType.sourceCode : editingSource.sourceType;

      // 构建请求数据
      const requestData = {
        $action: 'update',
        sourceId: editingSource.sourceId,
        sourceName: editingSource.sourceName,
        sourceCode: sourceCode,
        sourceType: editingSource.sourceType,
        endpoint: editingSource.endpoint || '',
        bucketName: editingSource.bucketName || '',
        basePath: editingSource.basePath || '',
        region: editingSource.region || '',
        secretId: editingSource.secretId ? parseInt(editingSource.secretId) : null,
        isPublic: editingSource.isPublic || 0,
        isEnabled: editingSource.isEnabled || 1,
        sourceStatus: editingSource.sourceStatus || 'ENABLED',
        isDefault: editingSource.isDefault ? 1 : 0,
        sourceOwner: editingSource.sourceOwner || null
      };

      const response = await http.post('/storage/stg-source/save', requestData);
      
      if (response.code === "200" || response.success) {
        setShowEditDialog(false);
        setEditingSource(null);
        refetch();
        alert('存储源更新成功');
      } else {
        throw new Error(response.msg || response.message || '更新失败');
      }
    } catch (error) {
      console.error('更新存储源失败:', error);
      alert(error.message || '更新存储源失败,请稍后重试');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDeleteSource = async (sourceId) => {
    if (!confirm('确定要删除这个存储源吗?')) {
      return;
    }

    try {
      const response = await http.post('/storage/stg-source/save', {
        $action: 'delete',
        sourceId: sourceId
      });
      
      if (response.code === "200" || response.success) {
        refetch();
        alert('存储源删除成功');
      } else {
        throw new Error(response.msg || response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除存储源失败:', error);
      alert(error.message || '删除存储源失败,请稍后重试');
    }
  };

  const handleSetDefault = async (sourceId) => {
    try {
      // 获取要设置为默认的存储源
      const source = storageSources.find(s => s.sourceId === sourceId);
      if (!source) {
        throw new Error('存储源不存在');
      }

      const response = await http.post('/storage/stg-source/save', {
        $action: 'update',
        sourceId: sourceId,
        sourceName: source.sourceName,
        sourceCode: source.sourceCode,
        sourceType: source.sourceType,
        endpoint: source.endpoint || '',
        bucketName: source.bucketName || '',
        basePath: source.basePath || '',
        region: source.region || '',
        secretId: source.secretId,
        isPublic: source.isPublic || 0,
        isEnabled: source.isEnabled || 1,
        sourceStatus: source.sourceStatus || 'ENABLED',
        isDefault: 1,
        sourceOwner: source.sourceOwner || null
      });
      
      if (response.code === "200" || response.success) {
        refetch();
        alert('已设置为默认存储源');
      } else {
        throw new Error(response.msg || response.message || '设置失败');
      }
    } catch (error) {
      console.error('设置默认存储源失败:', error);
      alert(error.message || '设置默认存储源失败,请稍后重试');
    }
  };

  const handleToggleStatus = async (sourceId) => {
    try {
      const source = storageSources.find(s => s.sourceId === sourceId);
      if (!source) {
        throw new Error('存储源不存在');
      }

      const newIsEnabled = source.isEnabled === 1 ? 0 : 1;
      const newSourceStatus = newIsEnabled === 1 ? 'ENABLED' : 'DISABLED';

      const response = await http.post('/storage/stg-source/save', {
        $action: 'update',
        sourceId: sourceId,
        sourceName: source.sourceName,
        sourceCode: source.sourceCode,
        sourceType: source.sourceType,
        endpoint: source.endpoint || '',
        bucketName: source.bucketName || '',
        basePath: source.basePath || '',
        region: source.region || '',
        secretId: source.secretId,
        isPublic: source.isPublic || 0,
        isEnabled: newIsEnabled,
        sourceStatus: newSourceStatus,
        isDefault: source.isDefault || 0,
        sourceOwner: source.sourceOwner || null
      });
      
      if (response.code === "200" || response.success) {
        refetch();
        alert(newIsEnabled === 1 ? '存储源已启用' : '存储源已停用');
      } else {
        throw new Error(response.msg || response.message || '操作失败');
      }
    } catch (error) {
      console.error('切换存储源状态失败:', error);
      alert(error.message || '操作失败,请稍后重试');
    }
  };

  const handleSourceSelect = (sourceId) => {
    setSelectedSources(prev => 
      prev.includes(sourceId) 
        ? prev.filter(id => id !== sourceId)
        : [...prev, sourceId]
    );
  };

  const handleSelectAll = () => {
    if (selectedSources.length === storageSources.length) {
      setSelectedSources([]);
    } else {
      setSelectedSources(storageSources.map(source => source.sourceId));
    }
  };

  const handleBatchDelete = async () => {
    if (selectedSources.length === 0) return;
    
    if (!confirm(`确定要删除选中的 ${selectedSources.length} 个存储源吗?`)) {
      return;
    }

    try {
      // 逐个删除选中的存储源
      for (const sourceId of selectedSources) {
        await http.post('/storage/stg-source/save', {
          $action: 'delete',
          sourceId: sourceId
        });
      }
      
      setSelectedSources([]);
      refetch();
      alert('批量删除成功');
    } catch (error) {
      console.error('批量删除失败:', error);
      alert('批量删除失败,请稍后重试');
    }
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                  <HardDrive className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    存储源管理
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    配置和管理文件存储源
                  </p>
                </div>
              </div>
            </div>

            <div className="flex items-center space-x-3">
              {selectedSources.length > 0 && (
                <Button 
                  variant="destructive" 
                  onClick={handleBatchDelete}
                >
                  <Trash2 className="w-4 h-4 mr-2" />
                  批量删除 ({selectedSources.length})
                </Button>
              )}

              <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
                <DialogTrigger asChild>
                  <Button className="bg-primary hover:bg-primary-600">
                    <Plus className="w-4 h-4 mr-2" />
                    添加存储源
                  </Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-4xl max-h-[80vh] overflow-hidden">
                  <DialogHeader>
                    <DialogTitle>添加存储源</DialogTitle>
                  </DialogHeader>
                  <div className="max-h-[60vh] overflow-y-auto pr-2">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="space-y-4">
                        <div>
                          <Label htmlFor="sourceName">存储源名称 <span className="text-red-500">*</span></Label>
                          <Input
                            id="sourceName"
                            value={newSource.sourceName}
                            onChange={(e) => setNewSource(prev => ({ ...prev, sourceName: e.target.value }))}
                            placeholder="请输入存储源名称"
                          />
                        </div>
                        
                        <div>
                          <Label htmlFor="sourceType">存储类型 <span className="text-red-500">*</span></Label>
                          <Select value={newSource.sourceType} onValueChange={(value) => setNewSource(prev => ({ ...prev, sourceType: value }))}>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {storageTypes.map(type => {
                                const IconComponent = type.icon;
                                return (
                                  <SelectItem key={type.value} value={type.value}>
                                    <div className="flex items-center space-x-2">
                                      <IconComponent className="w-4 h-4" />
                                      <span>{type.label}</span>
                                    </div>
                                  </SelectItem>
                                );
                              })}
                            </SelectContent>
                          </Select>
                        </div>

                        {newSource.sourceType === 'LOCAL' && (
                          <div>
                            <Label htmlFor="basePath">存储路径 <span className="text-red-500">*</span></Label>
                            <Input
                              id="basePath"
                              value={newSource.basePath}
                              onChange={(e) => setNewSource(prev => ({ ...prev, basePath: e.target.value }))}
                              placeholder="/var/www/storage"
                            />
                          </div>
                        )}

                        {['Amazon-S3', 'ALY_OSS', 'TXY_OSS', 'MINIO'].includes(newSource.sourceType) && (
                          <>
                            <div>
                              <Label htmlFor="endpoint">服务端点 <span className="text-red-500">*</span></Label>
                              <Input
                                id="endpoint"
                                value={newSource.endpoint}
                                onChange={(e) => setNewSource(prev => ({ ...prev, endpoint: e.target.value }))}
                                placeholder="https://s3.amazonaws.com"
                              />
                            </div>
                            <div>
                              <Label htmlFor="bucketName">存储桶名称 <span className="text-red-500">*</span></Label>
                              <Input
                                id="bucketName"
                                value={newSource.bucketName}
                                onChange={(e) => setNewSource(prev => ({ ...prev, bucketName: e.target.value }))}
                                placeholder="my-bucket"
                              />
                            </div>
                          </>
                        )}
                      </div>

                      <div className="space-y-4">
                        {['Amazon-S3', 'ALY_OSS', 'TXY_OSS', 'MINIO'].includes(newSource.sourceType) && (
                          <>
                            <div>
                              <Label htmlFor="region">区域</Label>
                              <Input
                                id="region"
                                value={newSource.region}
                                onChange={(e) => setNewSource(prev => ({ ...prev, region: e.target.value }))}
                                placeholder="us-east-1"
                              />
                            </div>
                            <div>
                              <Label htmlFor="secretId">密钥ID</Label>
                              <Input
                                id="secretId"
                                value={newSource.secretId}
                                onChange={(e) => setNewSource(prev => ({ ...prev, secretId: e.target.value }))}
                                placeholder="输入密钥ID"
                              />
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                  <DialogFooter>
                    <div className="flex items-center space-x-2 mr-auto">
                      <Switch
                        id="isDefault"
                        checked={newSource.isDefault}
                        onCheckedChange={(checked) => setNewSource(prev => ({ ...prev, isDefault: checked }))}
                      />
                      <Label htmlFor="isDefault">设置为默认存储源</Label>
                    </div>
                    <Button variant="outline" onClick={() => setShowAddDialog(false)} disabled={isSaving}>
                      取消
                    </Button>
                    <Button onClick={handleAddSource} disabled={isSaving}>
                      {isSaving ? (
                        <>
                          <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                          保存中...
                        </>
                      ) : (
                        '添加存储源'
                      )}
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 - 增加左右1%的margin */}
      <div className="flex-1 px-4 py-6 overflow-y-auto mx-[1%]">
        {/* 存储源列表 */}
        <Card>
          <CardContent className="p-0">
            {isLoading ? (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <div className="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                  <p className="text-material-grey-600">正在加载存储源列表...</p>
                </div>
              </div>
            ) : error ? (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-red-100 rounded-full flex items-center justify-center">
                  <AlertCircle className="w-8 h-8 text-red-600" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  加载失败
                </h3>
                <p className="text-material-grey-500 mb-4">
                  {error.message}
                </p>
                <Button onClick={() => refetch()} className="bg-primary hover:bg-primary-600">
                  重试
                </Button>
              </div>
            ) : storageSources.length === 0 ? (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <HardDrive className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  暂无存储源
                </h3>
                <p className="text-material-grey-500 mb-4">
                  点击上方按钮开始添加存储源
                </p>
                <Button onClick={() => setShowAddDialog(true)} className="bg-primary hover:bg-primary-600">
                  <Plus className="w-4 h-4 mr-2" />
                  添加存储源
                </Button>
              </div>
            ) : (
              <div>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12">
                        <input
                          type="checkbox"
                          checked={selectedSources.length === storageSources.length && storageSources.length > 0}
                          onChange={handleSelectAll}
                          className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                        />
                      </TableHead>
                      <TableHead>存储源信息</TableHead>
                      <TableHead className="hidden md:table-cell">类型</TableHead>
                      <TableHead className="hidden sm:table-cell">状态</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {storageSources.map((source) => (
                      <TableRow key={source.sourceId}>
                        <TableCell>
                          <input
                            type="checkbox"
                            checked={selectedSources.includes(source.sourceId)}
                            onChange={() => handleSourceSelect(source.sourceId)}
                            className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                          />
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center space-x-3">
                            <div className="w-10 h-10 bg-gradient-to-br from-purple-100 to-purple-200 rounded-lg flex items-center justify-center">
                              {getTypeIcon(source.sourceCode)}
                            </div>
                            <div>
                              <div className="flex items-center space-x-2">
                                <p className="font-medium text-material-grey-900">{source.sourceName}</p>
                                {source.isDefault === 1 && (
                                  <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-100">
                                    默认
                                  </Badge>
                                )}
                              </div>
                              <p className="text-sm text-material-grey-500">
                                {source.sourceCode === 'LOCAL' ? source.basePath : source.endpoint}
                              </p>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          <div className="flex items-center space-x-2">
                            {getTypeIcon(source.sourceCode)}
                            <span className="text-sm text-material-grey-700">
                              {getTypeLabel(source.sourceCode)}
                            </span>
                          </div>
                        </TableCell>
                        <TableCell className="hidden sm:table-cell">
                          {getStatusBadge(source.sourceStatus, source.isEnabled)}
                        </TableCell>
                        <TableCell className="text-right">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon">
                                <Settings className="w-4 h-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem onClick={() => handleEditSource(source)}>
                                <Edit className="w-4 h-4 mr-2" />
                                编辑
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => handleToggleStatus(source.sourceId)}>
                                <Eye className="w-4 h-4 mr-2" />
                                {source.isEnabled === 1 ? '停用' : '启用'}
                              </DropdownMenuItem>
                              {source.isDefault !== 1 && (
                                <DropdownMenuItem onClick={() => handleSetDefault(source.sourceId)}>
                                  <CheckCircle className="w-4 h-4 mr-2" />
                                  设为默认
                                </DropdownMenuItem>
                              )}
                              <DropdownMenuItem 
                                onClick={() => handleDeleteSource(source.sourceId)}
                                className="text-red-600"
                                disabled={source.isDefault === 1}
                              >
                                <Trash2 className="w-4 h-4 mr-2" />
                                删除
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 编辑存储源对话框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="sm:max-w-4xl max-h-[80vh] overflow-hidden">
          <DialogHeader>
            <DialogTitle>编辑存储源</DialogTitle>
          </DialogHeader>
          {editingSource && (
            <div className="max-h-[60vh] overflow-y-auto pr-2">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="edit-name">存储源名称 <span className="text-red-500">*</span></Label>
                    <Input
                      id="edit-name"
                      value={editingSource.sourceName}
                      onChange={(e) => setEditingSource(prev => ({ ...prev, sourceName: e.target.value }))}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="edit-type">存储类型</Label>
                    <Select 
                      value={editingSource.sourceType} 
                      onValueChange={(value) => setEditingSource(prev => ({ ...prev, sourceType: value }))}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {storageTypes.map(type => {
                          const IconComponent = type.icon;
                          return (
                            <SelectItem key={type.value} value={type.value}>
                              <div className="flex items-center space-x-2">
                                <IconComponent className="w-4 h-4" />
                                <span>{type.label}</span>
                              </div>
                            </SelectItem>
                          );
                        })}
                      </SelectContent>
                    </Select>
                  </div>

                  {editingSource.sourceType === 'LOCAL' && (
                    <div>
                      <Label htmlFor="edit-path">存储路径 <span className="text-red-500">*</span></Label>
                      <Input
                        id="edit-path"
                        value={editingSource.basePath}
                        disabled={true}
                        className="bg-material-grey-100 cursor-not-allowed"
                      />
                      <p className="text-xs text-material-grey-500 mt-1">编辑时不允许修改存储路径</p>
                    </div>
                  )}

                  {['Amazon-S3', 'ALY_OSS', 'TXY_OSS', 'MINIO'].includes(editingSource.sourceType) && (
                    <>
                      <div>
                        <Label htmlFor="edit-endpoint">服务端点 <span className="text-red-500">*</span></Label>
                        <Input
                          id="edit-endpoint"
                          value={editingSource.endpoint}
                          disabled={true}
                          className="bg-material-grey-100 cursor-not-allowed"
                        />
                        <p className="text-xs text-material-grey-500 mt-1">编辑时不允许修改服务端点</p>
                      </div>
                      <div>
                        <Label htmlFor="edit-bucket">存储桶名称 <span className="text-red-500">*</span></Label>
                        <Input
                          id="edit-bucket"
                          value={editingSource.bucketName}
                          disabled={true}
                          className="bg-material-grey-100 cursor-not-allowed"
                        />
                        <p className="text-xs text-material-grey-500 mt-1">编辑时不允许修改存储桶名称</p>
                      </div>
                    </>
                  )}
                </div>

                <div className="space-y-4">
                  {['Amazon-S3', 'ALY_OSS', 'TXY_OSS', 'MINIO'].includes(editingSource.sourceType) && (
                    <>
                      <div>
                        <Label htmlFor="edit-region">区域</Label>
                        <Input
                          id="edit-region"
                          value={editingSource.region}
                          onChange={(e) => setEditingSource(prev => ({ ...prev, region: e.target.value }))}
                        />
                      </div>
                      <div>
                        <Label htmlFor="edit-secretId">密钥ID</Label>
                        <Input
                          id="edit-secretId"
                          value={editingSource.secretId || ''}
                          onChange={(e) => setEditingSource(prev => ({ ...prev, secretId: e.target.value }))}
                        />
                      </div>
                    </>
                  )}

                  <div className="flex items-center space-x-2">
                    <Switch
                      id="edit-isDefault"
                      checked={editingSource.isDefault === true || editingSource.isDefault === 1}
                      onCheckedChange={(checked) => setEditingSource(prev => ({ ...prev, isDefault: checked }))}
                    />
                    <Label htmlFor="edit-isDefault">设为默认存储源</Label>
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDialog(false)} disabled={isSaving}>
              取消
            </Button>
            <Button onClick={handleUpdateSource} disabled={isSaving}>
              {isSaving ? (
                <>
                  <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  保存中...
                </>
              ) : (
                '保存更改'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default StorageSource;
